package com.sdy.resdir.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.approval.biz.model.TpApproveFlowConfig;
import com.sdy.common.utils.Assert;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.resdir.biz.mapper.RdResForOnlineMapper;
import com.sdy.resdir.biz.model.RdResForOnline;
import com.sdy.resdir.biz.model.RdResourceDir;
import com.sdy.resdir.biz.service.RdResForOnlineService;
import com.sdy.resdir.biz.service.RdResourceDirService;
import com.sdy.usercenter.api.UserQueryApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cgj
 * @since 2019-11-13
 */
@Slf4j
@Service
public class RdResForOnlineServiceImpl extends BaseServiceImpl<RdResForOnline> implements RdResForOnlineService {
    @Autowired
    private RdResForOnlineMapper rdResForOnlineMapper;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Value("${res.app.code}")
    private String appCode;
    @Value("${res.dept.code}")
    private String deptCode;
    @Value("${res.approval.authCode}")
    private String authCode;
    @Value("${res.approval.roleCode}")
    private String roleCode;

    /**
     * 新增配置模板
     * @param map
     * @param date
     * @param userId
     * @return
     */
    @Override
    public Boolean addConfigForOnline(Map<String, Object> map, Date date, Integer userId, Integer operateType) throws Exception {

        // 准备需要的数据
        Integer resId = (Integer) map.get("resId");
        String prefix = "[资源目录]-未归集";
        String strResId = prefix + resId;
        Integer resPower = (Integer) map.get("resPower");
        int roleId = userQueryApi.getRoleByCode(roleCode).getId();
        List<TpApproveFlowConfig> configs = approvalAllApi.selectApprovalByResId(strResId);
        List<Integer> deptIdList = new ArrayList<>();
        List<Integer> roleIdList = new ArrayList<>();
        if (operateType == 0) {
            LambdaUpdateWrapper<RdResourceDir> rdResourceDirWrapper = new LambdaUpdateWrapper<>();
            rdResourceDirWrapper.eq(RdResourceDir::getId, resId).set(RdResourceDir::getIsRelease, 1);
            boolean update = rdResourceDirService.update(rdResourceDirWrapper);
            Assert.notTrue(update, "更新资源为上线状态时出错!");
        }
        // 公开
        if (resPower == 1) {
            Integer idForApproval = userQueryApi.getDeptByCode(deptCode).getId();
            deptIdList.add(idForApproval);
            roleIdList.add(roleId);
            // 判断是否改变流程配置模板
            // 没有改变流程配置模板
            if (configs.size() == 1) {
                RdResourceDir oneDir = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId));
                oneDir.setId(resId).setResPower(resPower).setModifyTime(date);
                rdResourceDirService.updateById(oneDir);
                return true;
            } else if (configs.size() == 0) {
                // 调用流程配置接口
                String insertApproval = approvalAllApi.insertApproval(deptIdList, roleIdList, prefix, resId.toString());
                Assert.isTrue("移除配置失败".equals(insertApproval), "移除配置失败");
                Assert.isTrue(insertApproval.equals("缺失部门的对应角色"), "缺失部门的对应角色");
                Assert.isTrue(insertApproval.equals("缺失角色的对应部门"), "缺失角色的对应部门");
                Assert.notTrue(insertApproval.equals("流程生成成功"), "流程生成失败");
                // 同步dir里面的来源部门数据
                LambdaUpdateWrapper<RdResourceDir> upDir = new LambdaUpdateWrapper<>();
                upDir.eq(resId != null && !resId.equals(""), RdResourceDir::getId, resId)
                        .set(RdResourceDir::getResPowerDeptId, idForApproval)
                        .set(RdResourceDir::getResPowerDept, userQueryApi.getDeptByCode(deptCode).getName())
                        .set(RdResourceDir::getReleaseTime, date)
                        .set(resPower != null, RdResourceDir::getResPower, resPower)
                        .set(RdResourceDir::getModifyTime,date);
                Assert.notTrue(rdResourceDirService.update(upDir), "同步到dir时出错");
                return true;
            } else if (configs.size() == 2) {
                // 同步dir里面的来源部门数据
                LambdaUpdateWrapper<RdResourceDir> upDir = new LambdaUpdateWrapper<>();
                upDir.eq(resId != null && !resId.equals(""), RdResourceDir::getId, resId)
                        .set(RdResourceDir::getResPowerDeptId, idForApproval)
                        .set(RdResourceDir::getResPowerDept, userQueryApi.getDeptByCode(deptCode).getName())
                        .set(RdResourceDir::getReleaseTime, date)
                        .set(resPower != null, RdResourceDir::getResPower, resPower)
                        .set(RdResourceDir::getModifyTime,date);
                Assert.notTrue(rdResourceDirService.update(upDir), "同步到dir是出错");
                Integer lowerShelfRes = approvalAllApi.lowerShelfRes(deptIdList, roleIdList, prefix, resId, userId, date);
                Assert.notTrue(lowerShelfRes == 1, "重新发布失败！");
                return true;
            }
        } else if (resPower == 2) {
            Integer deptId = (Integer) map.get("deptId");
            Integer idForApproval = userQueryApi.getDeptByCode(deptCode).getId();
            // 若同一流程被同一部门的审批角色审批两次，则无意义
            Assert.isTrue(idForApproval.equals(deptId), "该流程被同一部门审批角色审批两次或以上!");
            deptIdList.add(idForApproval);
            roleIdList.add(roleId);
            deptIdList.add(deptId);
            roleIdList.add(roleId);
            if (configs.size() == 2 && configs.get(1).getAuditDepartmentId().equals(deptId)) {
                RdResourceDir oneDir = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery().eq(RdResourceDir::getId, resId));
                oneDir.setId(resId).setResPower(resPower).setModifyTime(date);
                rdResourceDirService.updateById(oneDir);
                return true;
            } else if (configs.size() == 0) {
                // 调用流程配置接口
                String insertApproval = approvalAllApi.insertApproval(deptIdList, roleIdList, prefix, resId.toString());
                Assert.isTrue(insertApproval.equals("移除配置失败"), "移除配置失败");
                Assert.isTrue(insertApproval.equals("缺失部门的对应角色"), "缺失部门的对应角色");
                Assert.isTrue(insertApproval.equals("缺失角色的对应部门"), "缺失角色的对应部门");
                Assert.notTrue(insertApproval.equals("流程生成成功"), "流程生成失败");
                // 同步dir里面的来源部门数据
                LambdaUpdateWrapper<RdResourceDir> upDir = new LambdaUpdateWrapper<>();
                upDir.eq(resId != null && !resId.equals(""), RdResourceDir::getId, resId)
                        .set(RdResourceDir::getResPowerDeptId, map.get("deptId"))
                        .set(RdResourceDir::getResPowerDept, userQueryApi.getDept((Integer) map.get("deptId")).getName())
                        .set(RdResourceDir::getReleaseTime, date)
                        .set(resPower != null, RdResourceDir::getResPower, resPower)
                        .set(RdResourceDir::getModifyTime,date);
                Assert.notTrue(rdResourceDirService.update(upDir), "同步到dir是出错");
                return true;
            } else if ((configs.size() == 2 && !configs.get(1).getAuditDepartmentId().equals(deptId)) || configs.size() == 1) {
                Integer lowerShelfRes = approvalAllApi.lowerShelfRes(deptIdList, roleIdList, prefix, resId, userId, date);
                Assert.notTrue(lowerShelfRes == 1, "重新发布失败！");
                // 同步dir里面的来源部门数据
                LambdaUpdateWrapper<RdResourceDir> upDir = new LambdaUpdateWrapper<>();
                upDir.eq(resId != null && !resId.equals(""), RdResourceDir::getId, resId)
                        .set(RdResourceDir::getResPowerDeptId, map.get("deptId"))
                        .set(RdResourceDir::getResPowerDept, userQueryApi.getDept((Integer) map.get("deptId")).getName())
                        .set(RdResourceDir::getReleaseTime, date)
                        .set(resPower != null, RdResourceDir::getResPower, resPower)
                        .set(RdResourceDir::getModifyTime,date);
                Assert.notTrue(rdResourceDirService.update(upDir), "同步到dir是出错");
                return true;
            }
        }
        return true;
    }
}
